package com.ebt.m.jpush;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.ebt.m.AppContext;
import com.ebt.m.R;
import com.ebt.m.activity.LoginActivity;
import com.ebt.m.commons.utils.Logger;
import com.ebt.m.commons.utils.SystemUtil;
import com.ebt.m.data.bean.UserInfo;


import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import cn.jpush.android.data.JPushLocalNotification;
import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;

/**
 * JPush API
 * Created by archer.qi on 2016/6/6.
 */
public class JPushUtil {

    public static List<OnJPushReceivedListener> mJPushListeners;

    public static final String TOPIC_BUSINESSOPPORTUNITY = "BusinessOpportunity";
    public static final String TOPIC_CHANGEAGENTVALIDATESTATUS = "ChangeAgentValidateStatus";

    // 初始化JPush
    public static void init(Context context) {
        JPushInterface.setDebugMode(true); // 开启调试
        JPushInterface.init(context);
        initJPushReceivedListeners();
    }

    // 添加组标签
    public static void setTags(Context context, Set<String> tags, TagAliasCallback callback) {
        JPushInterface.setTags(context, filterValidTags(tags), callback);
    }

    // 添加用户标签
    public static void setAlis(Context context, String alis, TagAliasCallback callback) {
        JPushInterface.setAlias(context, alis, callback);
    }

    // 过滤有效标签
    private static Set<String> filterValidTags(Set<String> tags) {
        return JPushInterface.filterValidTags(tags);
    }

    // 初始化JPush监听队列
    public static void initJPushReceivedListeners() {
        if (mJPushListeners == null) {
            mJPushListeners = new ArrayList<>();
        }
    }

    // 注册JPush监听事件
    public static void registerJPushReceivedListener(OnJPushReceivedListener listener) {
        initJPushReceivedListeners();
        if (listener != null && !mJPushListeners.contains(listener)) {
            mJPushListeners.add(listener);
        }
    }

    // 注销JPush监听事件
    public static void unregisterJPushReceivedListener(OnJPushReceivedListener listener) {
        if (mJPushListeners == null) {
            return;
        }
        if (listener != null && mJPushListeners.contains(listener)) {
            mJPushListeners.remove(listener);
        }
    }

    // 清空JPush监听事件
    public static void clearJPushReceivedListeners() {
        if (mJPushListeners == null) {
            return;
        }
        for (OnJPushReceivedListener listener : mJPushListeners) {
            listener = null;
        }
        mJPushListeners.clear();
        mJPushListeners = null;
    }

    // 更新JPush接收监听
    public static void updateJPushListeners(JPushResult result) {
        notifyAuthentication(result);
        if (mJPushListeners == null) {
            return;
        }
        for (OnJPushReceivedListener listener : mJPushListeners) {
            if (listener != null) {
                listener.onJPushReceived(result);
            }
        }
    }

    /**
     * 校验认证状态
     *
     * @param result
     */
    private static void notifyAuthentication(JPushResult result) {
        try {
            String topic = result.message.topic;
            if (!TextUtils.isEmpty(topic) && topic.equals(JPushUtil.TOPIC_CHANGEAGENTVALIDATESTATUS)) {
                Context context = AppContext.getInstance();
                int status = result.message.dataJson.getInt("status");
                JPushLocalNotification localNotification = new JPushLocalNotification();
                localNotification.setNotificationId(System.currentTimeMillis());
                localNotification.setTitle(context.getResources().getString(R.string.app_name));
                localNotification.setContent(status == 1 ? "您已成功认证公司模式,点击查看" : "您的认证已失效，如有疑问，请联系业管老师");
                localNotification.setExtras(result.message.toString());
                JPushInterface.addLocalNotification(AppContext.getInstance(), localNotification);
                if (status != 1) {
                    AppContext.clearLoginInfo(context);
                    Observable.just("")
                            .map(s -> SystemUtil.isBackground(AppContext.getInstance()))
                            .subscribeOn(Schedulers.io())
                            .subscribe(isBackground -> {
                                if (!isBackground) {
                                    Intent intent = new Intent(AppContext.getInstance(), LoginActivity.class);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                    AppContext.getInstance().startActivity(intent);
                                }
                            }, throwable -> Logger.e(throwable.getMessage()));
                }
            }
        } catch (Exception e) {
            Logger.e(e);
        }
    }

    // 获取注册ID
    public static String getRegisterID(Context context) {
        return JPushInterface.getRegistrationID(context);
    }

    // 清空所有的通知显示
    public void clearAllNotifications(Context context) {
        JPushInterface.clearAllNotifications(context);
    }

    // 根据ID移除通知显示
    public void clearNotificationById(Context context, int id) {
        JPushInterface.clearNotificationById(context, id);
    }

    // 校验Tag Alias 只能是数字,英文字母和中文
    public static boolean isValidTagAndAlias(String s) {
        Pattern p = Pattern.compile("^[\u4E00-\u9FA50-9a-zA-Z_-]{0,}$");
        Matcher m = p.matcher(s);
        return m.matches();
    }

    // JPush消息接收监听
    public interface OnJPushReceivedListener {
        public void onJPushReceived(JPushResult result);
    }


    ////////////////////////////////////////////////////

    // 用于覆盖当前有效的别名
    private static final String defaultCoveredAlis = "";

    /**
     * 设置用户别名
     *
     * @param context
     * @param alis
     */
    public static void setAlisAndTagsWhenLogin(Context context, String alis) {
//        if (null == alis || "".equals(alis)) {
//            throw new NullPointerException("Alis can not be null");
//        }
//        if (!isValidTagAndAlias(alis)) {
//            throw new IllegalStateException("Alis is not valid!");
//        }
        setAlis(context, alis, new TagAliasCallback() {
            @Override
            public void gotResult(int i, String s, Set set) {
                switch (i) {
                    case 0:
                        Logger.i("setAlis", "设置JPush别名成功！当前别名为： " + alis);
                        break;
                    default:
                        Logger.e("setAlis", getAlisErrorMessage(i));
                        break;
                }
            }
        });
        /**
         * 登录，获取到代理人的信息
         需要注册3个Tag:
         命名规则：
         AGENT_{agentId} ：针对代理人分组
         COMPANY_{companyId}   ：针对公司分组
         APP_ZYJ  ：  针对展业家APP
         */
        UserInfo userInfo = AppContext.getCurrentUser();
        int agentId = userInfo.getUserId();
        int companyId = userInfo.getCompanyInfo().getCompanyID();
        setJpushTags(context, "AGENT_" + agentId, "COMPANY_" + companyId, "APP_ZYJ");
    }

    /**
     * 设置Tag
     *
     * @param context
     * @param agentId
     * @param companyId
     * @param tagAPPZYJ
     */
    private static void setJpushTags(Context context, String agentId, String companyId, String tagAPPZYJ) {
        Set<String> set = new HashSet<>();
        set.add(agentId);
        set.add(companyId);
        set.add(tagAPPZYJ);
        setTags(context, set, new TagAliasCallback() {
            @Override
            public void gotResult(int i, String s, Set set) {
                switch (i) {
                    case 0:
                        Logger.i("setTags", "设置JPush Tag成功！");
                        break;
                    default:
                        Logger.e("setTags", getAlisErrorMessage(i));
                        break;
                }
            }
        });
    }

    /**
     * 注销用户别名
     *
     * @param context
     */
    public static void resetAlisAndTagsWhenLogout(Context context) {
        setAlis(context, defaultCoveredAlis, new TagAliasCallback() {
            @Override
            public void gotResult(int i, String s, Set set) {
                switch (i) {
                    case 0:
                        Logger.i("resetAlis", "注销JPush别名成功！");
                        break;
                    default:
                        Logger.e("setAlis", getAlisErrorMessage(i));
                        break;
                }
            }
        });
        setJpushTags(context, "", "", "");
    }

    // 根据错误码，生产错误信息
    private static String getAlisErrorMessage(int resultCode) {
        int index = -1;
        for (int i = 0; i < JPushError.ALIS_CODE.length; i++) {
            if (resultCode == JPushError.ALIS_CODE[i]) {
                index = i;
            }
        }
        if (index == -1) {
            return "设置Alis/Tags失败";
        }
        return "设置Alis/Tags发生异常，错误码： " + JPushError.ALIS_CODE[index] + ", 错误信息： "
                + JPushError.ALIS_MESSAGE[index] + "," + JPushError.ALIS_COMMAND;
    }

    /**
     * 根据onJPushReceived(int JPushType, String data)中的data,解析为JPushResult实体
     *
     * @param json
     * @return
     */
    public static JPushResult getJPushResult(String json) {
        return JPushData.getJPushResult(json);
    }

}
